package com.srv.servlet;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.srv.control.HashControl;
import com.srv.dao.DAOReserva;
import com.srv.dao.DAOUsuario;
import com.srv.dao.DAOVeiculo;
import com.srv.exceptions.UsuarioInvalidoException;
import com.srv.pojo.Reserva;
import com.srv.pojo.Usuario;
import com.srv.pojo.Veiculo;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static Logger LOG = Logger.getLogger(LoginServlet.class.getName());
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);

		if (session.getAttribute("email") != null) {
			String rs = session.getAttribute("email").toString() + "S.R.V";
			rs = HashControl.md5(rs);

			if (!session.getAttribute("controle").toString().equals(rs)) {
				RequestDispatcher view = request
						.getRequestDispatcher("index.jsp");
				view.forward(request, response);
			} else {
				RequestDispatcher view = request
						.getRequestDispatcher("principal.jsp");
				view.forward(request, response);
			}
		} else {
			RequestDispatcher view = request.getRequestDispatcher("index.jsp");
			view.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Usuario usuario = new Usuario();

		usuario.setEmail(request.getParameter("email"));
		usuario.setSenha(HashControl.md5(request.getParameter("senha")));

		DAOUsuario daoUsuario = null;
		HttpSession session = request.getSession();
		try {
			daoUsuario = new DAOUsuario();
			Integer x = daoUsuario.verificaLogin(usuario);
			if (x != 1){
				throw new UsuarioInvalidoException();
			}
			// Criação da sessão
			session.setAttribute("email", usuario.getEmail());
			session.setAttribute("controle",
					HashControl.md5(usuario.getEmail() + "S.R.V"));

			//Criar lista de reservas, caso exista
			//Estanciar obj de reserva
			//buscar dados de reserva no banco
			DAOReserva daoReserva = new DAOReserva();
			List<Reserva> listaReserva = daoReserva.getReservaList(usuario);
			
			session.setAttribute("reservas", listaReserva);
			
			DAOVeiculo daoVeiculo = new DAOVeiculo();
			List<Veiculo> listaVeiculo = daoVeiculo.getVeiculoList();
			session.setAttribute("veiculos", listaVeiculo);
			
			//redirecionar com o dispatcher atual
			
			//no jsp, criar o "for" para exibir a lista de reservas.
			//no jsp, criar link para cancelar e editar
			//no jsp, cancelar, criar cancelamento na reserva, executar sql de cancelamento e regras
			//no jsp, editar, criar tela de edição da reserva, executar sql de edição e regras
			
			RequestDispatcher view = request
					.getRequestDispatcher("principal.jsp");
			view.forward(request, response);
			
		} catch (UsuarioInvalidoException ue) {
			session.invalidate();
			request.setAttribute("msg",
					"Usuario nao encontrado, tente novamente ou cadastre-se");
			RequestDispatcher view = request.getRequestDispatcher("index.jsp");
			view.forward(request, response);
			
		} catch (Exception e) {
			LOG.log(Level.SEVERE, e.getMessage());
			e.printStackTrace();
		}

	}

}
